﻿using System;
using System.IO;
using System.Windows;
using System.Xml.Linq;
using Helpers;

namespace Util
{
    public static class ConnnectUtl
    {

        private static readonly XDocument ConnectInfoDoc = GetDoc("ConnectInfo.config");

        public static readonly string DbConnectStr = (string)GetConnectInfo("DB", "connnectStr");
        public static readonly string DbBackupStr = (string)GetConnectInfo("DBBackup", "backupStr");
        private static XDocument GetDoc(string configFilePath)
        {
            try
            {
                // 假设 configFilePath 是绝对路径
                if (!Path.IsPathRooted(configFilePath))
                {
                    configFilePath = Path.Combine(Directory.GetCurrentDirectory(), configFilePath);
                }

                if (!File.Exists(configFilePath))
                {
                    throw new FileNotFoundException($"配置文件未找到: {configFilePath}");
                }

                return XDocument.Load(configFilePath);
            }
            catch (Exception ex) {
                Logger.Instance.Error(ex, $"读取数据库配置文件{configFilePath}异常");
                return null;
            }
        }

        private static object GetConnectInfo(string elementName, string attributeName)
        {
            try
            {
                XDocument doc = ConnectInfoDoc;
                string attributeInfo = null;
                foreach (XElement element in doc.Descendants(elementName))
                {
                    attributeInfo = element.Attribute(attributeName).Value;
                }
                return attributeInfo;
            }
            catch(Exception ex)
            {
                Logger.Instance.Error(ex, $"解析数据库文件{elementName}异常");
                return null;
            }
          
        }

    }
}
